package com.lxb.store.service.Impl;

import com.lxb.store.dao.BuyGoodsDao;
import com.lxb.store.dao.UserDao;
import com.lxb.store.entity.BuyGoods;
import com.lxb.store.entity.ShopCar;
import com.lxb.store.entity.User;
import com.lxb.store.service.BuyGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service
public class BuyGoodsServiceImpl implements BuyGoodsService{

    @Autowired
    private BuyGoodsDao buyGoodsDao;

    @Autowired
    private UserDao userDao;

    @Override
    public BuyGoods save(BuyGoods buyGoods) {
        return buyGoodsDao.save(buyGoods);
    }



    /**
     * 判断购物车是否已存在该商品，若存在则更新数量并返回true，否则返回false
     * @param userName
     * @param goodsId
     * @param goodsName
     * @param goodsNum
     * @return
     */
    @Override
    public boolean checkBuyGoodsExist(String userName, Integer goodsId, String goodsName,int goodsNum,String color) {

        Integer shopCarId = userDao.getShopIdByUsername(userName);

        //没有购物车
        if(shopCarId == null){
            return  false;
        }

        BuyGoods buyGoods = buyGoodsDao.getByShopCarIdAndNameAndColor(shopCarId, goodsName,color);
        //判断是否之前购买过该商品
        if(buyGoods == null){
            return false;
        }
        //增加相同商品数量
        buyGoods.setNum(buyGoods.getNum()+goodsNum);

        //保存知道数据库
        BuyGoods saveBuyGoods = buyGoodsDao.save(buyGoods);
        if(saveBuyGoods == null){
            System.out.println("保存相同的商品数量失败！");
            return false;
        }
        return true;
    }

    @Override
    public Page<BuyGoods> findAll(Pageable pageable,String username) {


        User user = userDao.getByUsername(username);
        ShopCar shopCar = user.getShopCar();
        if(shopCar == null){
            System.out.println("该用户没购物车");
            return null;

        }

        return buyGoodsDao.findAll(new Specification<BuyGoods>() {
            @Override
            public Predicate toPredicate(Root<BuyGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                return criteriaBuilder.equal(root.get("shopCar"),shopCar);
            }
        },pageable);
    }

    @Override
    public void delete(Integer id) {
        buyGoodsDao.deleteById(id);
        return;
    }

    @Override
    public void deleteNum(List<Integer> ids) {
        buyGoodsDao.deleteBuyGoodsById(ids);
    }
}
